package routers

import (
	"encoding/json"
	"fmt"
	"net/http"
	"shqsoft.cn/pasnj/base"
	"shqsoft.cn/pasnj/entity"
	"strconv"

	//log "github.com/sirupsen/logrus"

	"github.com/labstack/echo"
)

//CompEditInrtAddRouter 路由：添加对公利率维护
func CompEditInrtAddRouter(c echo.Context) error {
	jlidStr := c.FormValue("jlid")
	inrtStr := c.FormValue("inrt")
	jlid, err := strconv.Atoi(jlidStr)
	if err != nil {
		return echo.NewHTTPError(http.StatusBadRequest, fmt.Errorf("参数jlid不能为空，并且必须为整数！"))
	}
	inrt, err := strconv.ParseFloat(inrtStr, 32)
	if err != nil {
		return echo.NewHTTPError(http.StatusBadRequest, fmt.Errorf("参数inrt不能为空，并且必须为数字！"))
	}
	sxrq := c.FormValue("sxrq")
	rows, err := base.DB.Raw("SELECT Inrt_flag FROM T_CM_CORP_CUST_DPSIT_ACCT_SUM_M WHERE jlid=?", jlid).Rows()
	if err != nil {
		return err
	}
	var (
		isInrt  bool
		message string
	)
	defer rows.Close()
	if rows.Next() {
		rows.Scan(&isInrt)
	}
	if !isInrt {
		err = base.DB.Exec("UPDATE T_CM_CORP_CUST_DPSIT_ACCT_SUM_M SET INRT=?,Inrt_flag=1 WHERE JLID=?", inrt, jlid).Error
		if err != nil {
			return echo.NewHTTPError(http.StatusBadRequest, err.Error())
		}
		err = base.DB.Exec("INSERT INTO T_COMP_ACCO_INRT_WH(JLID,SXRQ,INRT) VALUES(?,?,?)", jlid, sxrq, inrt).Error
		if err != nil {
			return echo.NewHTTPError(http.StatusBadRequest, err.Error())
		}
		message = "OK"
	} else {
		message = "NO"
	}
	return c.JSON(http.StatusOK, message)
}

//CompEditInrtEditRouter 路由：修改对公利率维护
func CompEditInrtEditRouter(c echo.Context) error {
	jlidStr := c.FormValue("jlid")
	jlid, err := strconv.Atoi(jlidStr)
	if err != nil {
		return echo.NewHTTPError(http.StatusBadRequest, fmt.Errorf("参数jlid不能为空，并且必须为整数！"))
	}
	jsonStr := c.FormValue("datas")
	if jsonStr == "" {
		return echo.NewHTTPError(http.StatusBadRequest, "datas不能为空！")
	}
	var datas []entity.DgckLLwhqk
	err = json.Unmarshal([]byte(jsonStr), &datas)
	if err != nil {
		return echo.NewHTTPError(http.StatusBadRequest, err.Error())
	}
	if l := len(datas); l == 0 {
		return echo.NewHTTPError(http.StatusBadRequest, "datas不能为空数组！")
	}
	tx := base.DB.Begin()
	for _, data := range datas {
		newData := entity.DgckLLwhqk{
			ACID: jlid,
			SXRQ: data.SXRQ,
			INRT: data.INRT,
		}
		err = base.DB.Save(&newData).Error
		if err != nil {
			tx.Rollback()
			return echo.NewHTTPError(http.StatusBadRequest, err.Error())
		}
		tx.Exec("EXEC UP_COMP_ACCO_LLWH ?,?,?", jlid, data.SXRQ, data.INRT)
	}
	//
	tx.Commit()
	return c.JSON(http.StatusOK, true)
}
